import { type PaginationProps } from "@pureadmin/table";
import { GetShareDataSelectList, ImportShareData, GetInterfaceDataInfo, GetUserApiFields } from "@/api/stu/bankBigData";
import { useRoute } from "vue-router";
import { ElMessage, FormInstance } from "element-plus";
import { ref, reactive, nextTick, watch, onMounted } from "vue";
export function useCommon() {
  const route = useRoute();
  const dataAccessVisible = ref<boolean>(false);
  const selectType = ref<string>()
  const selectList = ref<any>([]);
  const urlRegex = /^.{20,400}$/;// 校验20-400个字中文
  const passwordRegex = /^.{0,12}$/ //检验0-12个数字或者字母
  const dataList = ref<any>([]);
  const loading = ref<boolean>(false);
  const BtnLoading = ref<boolean>(false)
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 30,
    currentPage: 1,
    background: true,
    pageSizes: [5, 10, 30],
  });
  const columnHead = ref([])
  const columns = ref([]);

  const dataAccessFrom = reactive({
    url: '',
    password: '',
  })

  const rule = {
    url: [
      {
        required: true,
        validator: (rule: any, value: any, callback: () => void) => {
          if (urlRegex.test(dataAccessFrom.url) === false) {
            return callback(new Error('请输20-400个字符'))
          } else {
            // 校验通过
            return callback()
          }
        },
        trigger: ["blur", "change"],
      }
    ],
    password: [
      {
        validator: (rule: any, value: any, callback: () => void) => {
          if (passwordRegex.test(dataAccessFrom.password) === false) {
            return callback(new Error('请输0-12位密码'))
          } else {
            // 校验通过
            return callback()
          }
        },
        trigger: ["blur", "change"],
      }
    ],
  }

  //获取列表数据
  async function getList() {
    const data1 = {
      taskId: route.query.taskId,
      planId: route.query.planId,
      detailId: selectList.value.find(item => item.selectName == selectType.value).userApiInfoIds
    }
    const respone1 = await GetUserApiFields(data1)
    if (respone1.success) {
      columns.value = []
      columnHead.value = respone1.data
      columnHead.value = columnHead.value.sort((a, b) => a.sortNo - b.sortNo);
      columnHead.value = columnHead.value.filter(item => item.fieldName !== "ID");
      console.log(columnHead.value);
      columns.value = columnHead.value.map(item => {
        return { prop: item.apiDataField, label: item.remark, minWidth: 180 };
      });
      columns.value.unshift({
        label: "序号",
        type: "index",
        minWidth: 50
      })
    }

    const data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
      pageIndex: pagination.currentPage,
      pageCount: pagination.pageSize,
      userApiInfoIds: selectList.value.find(item => item.selectName == selectType.value).userApiInfoIds
    };
    const respone = await GetInterfaceDataInfo(data);
    if (respone.success) {
      pagination.total = respone.data.totalCount;
      dataList.value = respone.data.items;
    } else {
      ElMessage.error(respone.msg);
    }
  }
  //导入数据
  const saveDataAccess = (shareFrom: FormInstance | undefined) => {
    (shareFrom as any).validate(async valid => {
      if (!valid) return;
      const data = {
        taskId: route.query.taskId,
        planId: route.query.planId,
        shareUrl: dataAccessFrom.url,
        pwd: dataAccessFrom.password
      };
      BtnLoading.value = true;
      OUTBtnLoding()
      const respone = await ImportShareData(data);
      if (respone.success) {
        ElMessage.success(respone.msg)
        const respone1 = await GetShareDataSelectList({
          taskId: route.query.taskId,
          planId: route.query.planId,
        });
        if (respone1.success) {
          selectList.value = respone1.data
        } else {
          ElMessage.error(respone1.msg);
        }
        cancelDataAccess()
      } else {
        ElMessage.error(respone.msg);
      }
    })
  }


  //取消新建分享
  function cancelDataAccess() {
    for (var prop in dataAccessFrom) {
      if (dataAccessFrom.hasOwnProperty(prop)) {
        dataAccessFrom[prop] = ''
      }
    }
    dataAccessVisible.value = false
  }
  function handleSizeChange(val) {
    getList()
  }
  function handleCurrentChange(val) {
    getList()
  }
  onMounted(async () => {
    const respone = await GetShareDataSelectList({
      taskId: route.query.taskId,
      planId: route.query.planId,
    });
    if (respone.success) {
      selectList.value = respone.data
    } else {
      ElMessage.error(respone.msg);
    }
  })

  function OUTBtnLoding() {
    setTimeout(() => {
      BtnLoading.value = false
    }, 1000)
  }


  watch(selectType, newValue => {
    getList()
  });

  return {
    dataList,
    loading,
    pagination,
    columns,
    BtnLoading,
    dataAccessVisible,
    dataAccessFrom,
    rule,
    selectType,
    selectList,
    saveDataAccess,
    cancelDataAccess,
    handleCurrentChange,
    handleSizeChange,
  }
}
